<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form inline @submit.native.prevent="search">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.queryConditions"
                clearable
                placeholder=""
                prefix-icon="el-icon-search"
                size="medium"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="searchForm.state"
                size="medium"
                style="width: 100px"
                @change="stateSelected"
              >
                <!-- <el-option :value="0" label="全部"></el-option> -->
                <el-option value="0" label="已审核" />
                <el-option value="1" label="已通过" />
                <el-option value="-1" label="已驳回" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="组织">
              <el-select v-model="organizationList.organizeName" clearable placeholder="全部" style="width:150px;" @change="organizationSelected">
                <el-option v-for="item in organizationList" :key="item.id" :value="item.id" :label="item.organizeName" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button native-type="submit" size="medium" type="primary"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-button icon="el-icon-download" type="primary" class="btn">
            <a download :href="exportUrl"> 导出 </a>
          </el-button>

          <!-- <el-button
            class="btn"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="addManagerDialog"
            >添加</el-button
          > -->
          <!-- <el-upload
            class="upload-demo"
            :action="uploadURL"
            :headers="headers"
            :show-file-list="false"
            :on-success="onSuccess"
            :on-error="onError"
          >
            <el-button icon="el-icon-upload2" type="primary"
              >点击上传</el-button
            >
          </el-upload> -->
        </el-col>
      </el-row>
      <div>
        <el-table
          :data="list"
          border
          style="width: 100%"
          v-loading="auditedSupplierLoading"
        >
          <el-table-column
            type="index"
            width="50"
            label="序号"
            align="center"
          />
          <el-table-column label="头像" width="70" align="center">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.avatar"></el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column prop="email" label="邮箱" align="center" />
          <el-table-column prop="applyTime" label="申请时间" align="center" />
          <el-table-column label="当前状态" align="center">
            <template slot-scope="scope">
              <font style="color: red">{{
                stateConvert(scope.row.state)
              }}</font>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-tooltip content="查看信息" placement="top">
                <el-button
                  size="mini"
                  icon="el-icon-search"
                  circle
                  @click="showDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                content="为其分组"
                placement="top"
                v-show="scope.row.state === 1"
              >
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editManagerDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="移除供应商" placement="top">
                <el-button
                  size="mini"
                  el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteSupplier(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <Dialog
        :visible="supplierAuditedVisible"
        :main-info="supplierMainInfo"
        :other-info="supplierOtherInfo"
        @cancel="cancel"
      />
      <edit-dialog
        :index="index"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :main-info="supplierMainInfo"
        @cancel="cancel"
        @ok="ok"
      />
    </el-card>
  </div>
</template>

<script>
import {
  deleteSupplierInfo,
  getAllAuditedSupplierInfoByConditions,
  getSupplierOtherInfo,
  supplierGrouping,
} from "@/api/supplier.js";
import Dialog from "./components/Dialog";
import EditDialog from "./components/editDialog";

export default {
  name: "SupplierAuditedManage",
  components: { Dialog, EditDialog },
  data() {
    return {
      searchForm: {
        state: 0+"", // -1  1 之外的其他数字都是查询所有
        queryConditions: "",
      },
      list: [],
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      supplierAuditedVisible: false,
      supplierMainInfo: {},
      supplierOtherInfo: {},
      editDialogVisible: false,
      auditedSupplierLoading: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑；2 查看信息
      // headers: {
      //   Authorization: getToken(),
      // },
    };
  },
  computed: {
    exportUrl() {
      return (
        process.env.VUE_APP_BASE_API +
        "/manager/exportSupplierManInfoExcel/" +
        this.$store.getters.accountId +
        "/?state=" +
        this.searchForm.state
      );
    },
  },
  created() {
    this.auditedSupplierLoading = true;
    this.getData();
    // this.getOrganizations()
    // console.log(getToken())
  },
  methods: {
    stateConvert(state) {
      if (state === 1) {
        return "已通过";
      } else {
        return "已拒绝";
      }
    },
    // async getOrganizations() {
    //   const result = await getAllOrganizationInfos()
    //   this.organizationList = result.data
    //   // console.log('@@@@',this.organizationList)
    // },
    search() {
      this.paging.current = 1;
      this.auditedSupplierLoading = true;

      this.getData();
    },
    getData() {
      const form = {
        ...this.searchForm,
        managerId: this.$store.getters.accountId,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      getAllAuditedSupplierInfoByConditions(form)
        .then(({ data }) => {
          console.log(data);
          this.list = data.supplierInfos;
          //this.paging.size = data.size
          this.paging.total = data.totalCount;
          this.auditedSupplierLoading = false;
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.auditedSupplierLoading = false;
        });
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    showDialog(row) {
      this.supplierAuditedVisible = true;
      this.supplierMainInfo = this.extendCopy(row);
      getSupplierOtherInfo({ supplierId: row.id }).then((res) => {
        if (res.code === 200) {
          this.supplierOtherInfo = res.data;
        }
      });
      this.index = 2;
    },
    deleteSupplier(row) {
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await deleteSupplierInfo({
            supplierId: row.id,
            accountId: this.$store.getters.accountId,
          });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    stateSelected(val) {
      this.searchForm.state = val;
      this.search();
    },
    editManagerDialog(row) {
      this.dialogTitle = "供应商分组";
      this.editDialogVisible = true;
      this.supplierMainInfo = this.extendCopy(row);
      this.index = 1;
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) {
        c[i] = p[i];
      }
      return c;
    },
    // addManagerDialog() {
    //   this.dialogTitle = "添加管理员";
    //   this.editDialogVisible = true;
    //   this.index = 0;
    // },
    cancel() {
      if (this.index === 2) {
        this.supplierAuditedVisible = false;
      } else {
        this.editDialogVisible = false;
      }
      this.index = 0;
    },
    editsupplierMainInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑导师信息
          // console.log(val)
          const result = await supplierGrouping(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("分组成功");
            resolve(result);
          } else {
            this.$message.error("分组失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editsupplierMainInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    // onSuccess(response, file, fileList) {
    //   console.log(response);
    //   if (response.code !== 200) {
    //     this.$message.error("上传失败，请重试");
    //   } else {
    //     this.$message.success("上传成功");
    //     this.getData();
    //   }
    // },
    // onError(error, file, fileList) {
    //   console.log(error);
    // },
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
</style>
